<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <!-- <el-form-item label="上级ID" prop="parentId">
            <el-input v-model="queryParams.parentId" placeholder="请输入上级ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" clearable>
              <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="设备系列" prop="series">
            <el-select v-model="queryParams.series" placeholder="请选择设备系列" clearable>
              <el-option v-for="dict in face_device_series" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="设备IP" prop="ip">
            <el-input v-model="queryParams.ip" placeholder="请输入设备IP" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="唯一码" prop="guid">
            <el-input v-model="queryParams.guid" placeholder="请输入设备唯一码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="安装区域" prop="area">
            <el-select v-model="queryParams.area" placeholder="请选择安装区域" clearable>
              <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="安装位置" prop="location">
            <el-input v-model="queryParams.location" placeholder="请输入安装位置" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="安装方向" prop="position">
            <el-select v-model="queryParams.position" placeholder="请选择安装方向" clearable>
              <el-option v-for="dict in device_position" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="onlineStatus">
            <el-select v-model="queryParams.onlineStatus" placeholder="请选择状态" clearable>
              <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="最后在线时间" prop="offlineTime">
            <el-date-picker clearable v-model="queryParams.offlineTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择最后在线时间" />
          </el-form-item> -->
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in use_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Refresh" @click="handleSync" v-hasPermi="['device:analyse:sync']">同步设备信息</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="User" @click="handleSyncUser" v-hasPermi="['device:analyse:syncUser']">同步人员信息</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        height="calc(100vh - 360px)"
        v-loading="loading"
        :data="deviceInfoList"
        row-key="id"
        stripe
        ref="deviceInfoTableRef"
        @row-dblclick="(row)=>handleDetail(row)"
      >
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <!-- <el-table-column label="上级ID" align="center" prop="parentId" /> -->
        <!-- <el-table-column label="类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.type" />
          </template>
        </el-table-column> -->
        <el-table-column label="设备名称" align="center" prop="name" />
        <el-table-column label="设备类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="设备系列" align="center" prop="series">
          <template #default="scope">
            <dict-tag :options="face_device_series" :value="scope.row.series" />
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="设备IP" align="center" prop="ip" /> -->
        <!-- <el-table-column label="设备编码" align="center" prop="deviceCode" />
        <el-table-column label="设备唯一码" align="center" prop="guid" /> -->
        <el-table-column label="安装区域" align="center" prop="area">
          <template #default="scope">
            <dict-tag :options="device_area" :value="scope.row.area" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="安装位置" align="center" prop="location" /> -->
        <el-table-column label="安装方向" align="center" prop="position">
          <template #default="scope">
            <dict-tag :options="device_position" :value="scope.row.position" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="onlineStatus">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.onlineStatus" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="最后在线时间" align="center" prop="offlineTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.offlineTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <!-- <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="use_status" :value="scope.row.status" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" />
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:DeviceInfo:remove']" />
            </el-tooltip>
            <el-tooltip content="添加附属设备" placement="top" v-if="scope.row.type==2">
              <el-button link type="primary" class="btn" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['device:DeviceInfo:add']"
                >添加附属设备</el-button
              >
            </el-tooltip>
            <el-tooltip content="一键重启" placement="top" v-if="scope.row.onlineStatus==2">
              <el-button link type="success" class="btn" @click="handleAdd(scope.row)">一键重启</el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改人脸分析盒对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="740px" append-to-body>
      <el-form
        ref="deviceInfoFormRef"
        :inline="true"
        :model="form"
        :rules="form.type == 2?rules:rules2"
        label-width="100px"
        class="add-form"
        disabled
      >
        <!-- <el-form-item label="上级ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入上级ID" />
        </el-form-item> -->
        <!-- <el-form-item label="设备类型" prop="type" v-if="[3,4].includes(form.type)">
          <el-select v-model="form.type" placeholder="请选择设备类型">
            <el-option v-for="dict in fs_device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType" v-if="form.type==2">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" disabled>
            <el-option v-for="dict in face_device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备系列" prop="series">
          <el-select v-model="form.series" placeholder="请选择设备系列">
            <el-option v-for="dict in face_device_series" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- 类型：0闸机，1 智能摄像头 2 智能面板机 3 智能服务器 4 网络摄像机 5 存储服务器 6、门禁控制器 -->
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择设备类型">
            <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入设备IP" />
        </el-form-item>
        <el-form-item label="设备Mac" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入设备MAC" />
        </el-form-item>
        <!-- <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备唯一码" prop="guid">
          <el-input v-model="form.guid" placeholder="请输入设备唯一码" s />
        </el-form-item> -->
        <el-form-item label="安装区域" prop="area">
          <el-select v-model="form.area" placeholder="请选择安装区域">
            <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装方向" prop="position">
          <el-select v-model="form.position" placeholder="请选择安装方向">
            <el-option v-for="dict in device_position" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="location" style="width: 95%">
          <el-input v-model="form.location" placeholder="请输入安装位置" />
        </el-form-item>
        <el-form-item label="取流地址" prop="location" style="width: 95%">
          <el-input v-model="form.rtspUrl" placeholder="请输入取流地址" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="onlineStatus">
          <el-select v-model="form.onlineStatus" placeholder="请选择状态">
            <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="最后在线时间" prop="offlineTime">
          <el-date-picker clearable v-model="form.offlineTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后在线时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark" style="width: 95%">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in use_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="DeviceInfo" lang="ts">
import {
  listDeviceInfo,
  getDeviceInfo,
  delDeviceInfo,
  addDeviceInfo,
  updateDeviceInfo,
  syncAiotDeviceList,
  syncAiotUserInfo
} from '@/api/device/deviceInfo';
import { DeviceInfoVO, DeviceInfoQuery, DeviceInfoForm } from '@/api/device/deviceInfo/types';

type DeviceInfoOption = {
  id: number;
  name: string;
  children?: DeviceInfoOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { device_position, device_type, use_status, face_device_series, device_area, online_status, face_device_type, fs_device_type } = toRefs<any>(
  proxy?.useDict(
    'device_position',
    'device_type',
    'use_status',
    'face_device_series',
    'device_area',
    'online_status',
    'face_device_type',
    'fs_device_type'
  )
);

const deviceInfoList = ref<DeviceInfoVO[]>([]);
const deviceInfoOptions = ref<DeviceInfoOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const deviceInfoFormRef = ref<ElFormInstance>();
const deviceInfoTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceInfoForm = {
  id: undefined,
  uuid: undefined,
  parentId: undefined,
  type: '1,2,3,4,5,6',
  name: undefined,
  series: undefined,
  ip: undefined,
  deviceCode: undefined,
  guid: undefined,
  area: undefined,
  location: undefined,
  position: undefined,
  onlineStatus: 1,
  offlineTime: undefined,
  remark: undefined,
  deviceType: undefined,
  mac: undefined,
  userName: undefined,
  userPassword: undefined,
  status: 1
};

const data = reactive<PageData<DeviceInfoForm, DeviceInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    // pageNum: 1,
    // pageSize: 10,
    parentId: undefined,
    type: '1,2,3,4,5,6',
    name: undefined,
    series: undefined,
    ip: undefined,
    deviceCode: undefined,
    guid: undefined,
    area: undefined,
    location: undefined,
    position: undefined,
    onlineStatus: undefined,
    offlineTime: undefined,
    deviceType: undefined,
    status: 1,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    series: [{ required: true, message: '设备系列不能为空', trigger: 'change' }],
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    guid: [{ required: true, message: '设备唯一码不能为空', trigger: 'blur' }],
    area: [{ required: true, message: '安装区域', trigger: 'change' }],
    userName: [{ required: true, message: '设备账号不能为空', trigger: 'blur' }],
    userPassword: [{ required: true, message: '设备密码不能为空', trigger: 'blur' }]
  },
  rules2: {
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    series: [{ required: true, message: '设备系列不能为空', trigger: 'change' }],
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    guid: [{ required: true, message: '设备唯一码不能为空', trigger: 'blur' }],
    area: [{ required: true, message: '安装区域', trigger: 'change' }],
    userName: [{ required: true, message: '设备账号不能为空', trigger: 'blur' }],
    userPassword: [{ required: true, message: '设备密码不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules, rules2 } = toRefs(data);

/** 查询人脸分析盒列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceInfo(queryParams.value);
  deviceInfoList.value = res.rows;
  loading.value = false;
  // const data = proxy?.handleTree<DeviceInfoVO>(res.rows, 'id', 'parentId');
  // if (data) {
  //   deviceInfoList.value = data;
  //   loading.value = false;
  // }
};

/** 查询人脸分析盒下拉树结构 */
const getTreeselect = async () => {
  const res = await listDeviceInfo();
  deviceInfoOptions.value = [];
  const data: DeviceInfoOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<DeviceInfoOption>(res.rows, 'id', 'parentId');
  deviceInfoOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  deviceInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: DeviceInfoVO) => {
  reset();
  // getTreeselect();
  form.value.parentId = undefined;
  if (row != null && row.id) {
    form.value.parentId = row.id;
    form.value.type = 3;
    dialog.title = '添加附加设备';
  } else {
    form.value.parentId = 0;
    form.value.deviceType = 1;
    form.value.type = 2;
    dialog.title = '添加人脸分析盒';
  }
  dialog.visible = true;
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(deviceInfoList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: DeviceInfoVO[], status: boolean) => {
  data.forEach((item) => {
    deviceInfoTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: DeviceInfoVO) => {
  reset();
  // await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  // form.value.deviceType = row.deviceType;
  const res = await getDeviceInfo(row.id);
  Object.assign(form.value, res.data);
  if (form.value.type == 2) {
    dialog.title = '修改人脸分析盒';
  } else {
    dialog.title = '修改附加设备';
  }
  dialog.visible = true;
};

const handleDetail = async (row: DeviceInfoVO) => {
  reset();
  // await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  // form.value.deviceType = row.deviceType;
  const res = await getDeviceInfo(row.id);
  Object.assign(form.value, res.data);
  dialog.title = '详情';
  dialog.visible = true;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/deviceInfo/export',
    {
      ...queryParams.value
    },
    `deviceInfo_${new Date().getTime()}.xlsx`
  );
};

/** 提交按钮 */
const submitForm = () => {
  deviceInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: DeviceInfoVO) => {
  await proxy?.$modal.confirm('是否确认删除人脸分析盒编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delDeviceInfo(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleSync = async () => {
  await proxy?.$modal.confirm('是否确认同步鸿图设备信息？');
  loading.value = true;
  const res = await syncAiotDeviceList().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess(`同步完成，新增设备数量：${res.data.addCount}，更新设备数量：${res.data.updateCount}`);
  await getList();
};
const handleSyncUser = async () => {
  await proxy?.$modal.confirm('是否同步用户信息至鸿图系统？');
  loading.value = true;
  const res = await syncAiotUserInfo().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess(`同步完成，成功数量：${res.data.successesCount}，失败数量：${res.data.failuresCount}`);
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.btn {
  border: 1px solid #dcdfe6;
  border-radius: 20px;
  padding: 5px 10px;
}
</style>
